<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-06-21
 * Time: 16:54:31
 * Info:
 */

namespace app\common\model;

use app\common\model\UserLog as UserLogModel;
use app\common\model\UserToken as UserTokenModel;

class User extends Common
{

    /**
     * 用户账户密码登陆
     * @param array $data 用户登陆信息
     * @param int $loginType 1就是默认的，存session，2就是返回user_token
     * @param int $platform 平台id，主要和session有关系 1就是默认的平台，，2就是微信小程序平台，当需要放回user_token的时候，会用到此字段
     */
    public function toLogin($data, $loginType = 1, $platform = 1)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => ''
        ];

        if (empty($data['mobile']) || empty($data['password'])) {
            $result['msg'] = '用户名手机号或者密码不能为空';

            return $result;
        }
        //校验验证码

        //查询会员信息
        $userInfo = $this->where(['username' => $data['mobile']])->whereOr(['mobile' => $data['mobile']])->find();
        if (empty($userInfo)) {
            $result['msg'] = '没有找到此账号';

            return $result;
        }

        //验证密码
        $userPassword = $userInfo['password'];
        $postPass     = cmf_password($data['password'], $userInfo['salt']);
        if ($userPassword != $postPass) {
            $result['msg'] = '密码错误，请重试';

            return $result;
        }
        if ($userInfo['status'] == 0) {
            $result['msg'] = '该账号已停用';

            return $result;
        }
        $result = $this->setSession($userInfo, $loginType, $platform);//根据登陆类型，去存session，或者是返回user_token

        return $result;

    }

    /**
     *设置用户登录信息或者更新用户登录信息
     * @param     $userInfo
     * @param     $data
     * @param     $loginType 登陆类型1是存session，主要是商户端的登陆和网页版本的登陆,2就是token
     * @param int $platform 1就是普通的登陆
     * @param int $type 1的话就是登录,2的话就是更新
     * @return array
     */
    public function setSession($userInfo, $loginType, $platform = 1, $type = 1)
    {
        $result   = [
            'code' => 0,
            'data' => '',
            'msg'  => ''
        ];
        $userInfo = $userInfo->toArray();
        //判断账号状态
        if ($userInfo['status'] != 1) {
            $result['msg'] = '该账号已停用';

            return $result;
        }
        switch ($loginType) {
            case 1:
                session('user', $userInfo);
                $result['code'] = 200;
                break;
            case 2:
                $userTokenModel = new UserTokenModel();
                $result         = $userTokenModel->setToken($userInfo['id'], $platform);
                break;
        }

        if ($type == 1) {
            //添加登录日志
            $userLogModel = new UserLogModel();
            //$userLogModel->setLog($userInfo['id'], $userLogModel::USER_LOGIN, ['会员登录成功']);
        }

        return $result;
    }

}
